#include <avr/io.h>
#include <avr/interrupt.h>
#include <stdlib.h>
#include <avr/wdt.h>
#ifndef F_CPU
#define F_CPU 8000000UL
#endif
#include <util/delay.h>
char output2[10] = {0b01111110,0b01001000, 0b00111101, 0b01101101, 0b01001011, 0b01100111, 0b01110111, 0b01001100, 0b01111111, 0b01101111};
uint16_t temp = 0;
uint16_t number = 0;
uint32_t voltage = 0;
uint16_t display = 0;
uint8_t digit1 = 0;
uint8_t digit2 = 0;
uint8_t digit3 = 0;


void calc(void)
{
    temp = display;
    digit3 = temp % 10; //last digit
    temp /= 10;
    digit2 = temp % 10;//second digit
    temp /= 10;
    digit1 = temp;//first digit
}
void AdcInit(void) //free running
{
    ADCSRA |= (1<<ADPS2) | (1<<ADPS1);
    ADMUX |= (1<<REFS0);
    // ADMUX |= (1<<ADLAR);
    ADCSRA |= (1<<ADFR);
    ADCSRA |= (1<<ADEN);
    ADCSRA |= (1<<ADSC);
}
void TCNT0Init(void)
{
    TCCR0 = (1<<CS01) |(1<<CS00);//divide clock by 64    8Mhz / 64 = 125000hz
    TIMSK |= (1<<TOIE0);

}
int main (void)
{
    calc();
    DDRD = 0xFF;
    DDRB = 0b00000111;

    //pb0 last digit
    //pb1 second digit
    //pb2 first digit
    //TCNT0Init();
    AdcInit();
    while (1)
    {
        PORTB = 0b00000001;
        PORTD = output2[digit3];

        calc();
        PORTD = 0;
        PORTB = 0;

        PORTB = 0b00000010;
        PORTD = output2[digit2];

        calc();
        PORTD = 0;
        PORTB = 0;

        PORTB = 0b00000100;
        PORTD = output2[digit1];
        PORTD |= 0b10000000;

        calc();
        PORTD = 0;
        PORTB = 0;

        voltage = ADCW * 5; //Vin = ADC * VREF /1024     ADC = VIN*1024/Vref
        voltage *= 100;
        voltage /= 1024;
        display = voltage;
        //display = ADCW;
    }
}

